package com.example.hotfix;

/*
 * author: caojunhao
 * date  : 2021/1/5
 * desc  :
 */

import java.lang.reflect.Field;
import java.lang.reflect.Method;

public class ShareReflectUtil {

    public static Field findField(Object instance,String name){
        Class<?> aClass = instance.getClass();
        Field declaredField;
        while(aClass!=Object.class) {
            try {
                //获取当前类的所有类型的变量
                declaredField = aClass.getDeclaredField(name);
                if (declaredField != null) {
                    declaredField.setAccessible(true);
                    return declaredField;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            aClass=aClass.getSuperclass();
        }
        throw new RuntimeException("field no found");
    }

    public static Method findMethod(Object instance, String name, Class<?>... parameterTypes){
        Class<?> aClass = instance.getClass();
        Method declaredMethod;
        while(aClass!=Object.class) {
            try {
                declaredMethod = aClass.getDeclaredMethod(name,parameterTypes);
                if (declaredMethod != null) {
                    declaredMethod.setAccessible(true);
                    return declaredMethod;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            aClass=aClass.getSuperclass();
        }
        throw new RuntimeException("method no found");
    }
}
